package com.itheima.springbootwebtlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.annotation.LogOperation;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.ClazzMapper;
import com.itheima.springbootwebtlias.mapper.StudentMapper;
import com.itheima.springbootwebtlias.pojo.Clazz;
import com.itheima.springbootwebtlias.pojo.ClazzQueryParam;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    // 分页查询
    @LogOperation
    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        // 1.设置PageHelper分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        // 2.执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        // 3.封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @LogOperation
    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @LogOperation
    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @LogOperation
    @Override
    public void update(Clazz clazz) {
        clazzMapper.update(clazz);
    }

    // 删除班级
    @LogOperation
    @Override
    public void deleteById(Integer id) {
        // 0.查询当前班级下是否存在学生
        // 1.如果存在学生，提示部门下存在学生，不允许删除
        Integer count = studentMapper.isHasEmpByDeptId(id);
        if(count != 0){
            throw new DeletionIsNotAllowed("班级里还有学生，不允许删除");
        }
        clazzMapper.deleteById(id);
    }

    @LogOperation
    @Override
    public List<Clazz> selectALL() {
        return clazzMapper.selectALL();
    }
}
